#!/usr/bin/perl
#
# Deduce login times from log data
# Quite weird...
#
use Counter;
use DBI;
use HTTP::Date;

$limit = shift;
$limit = 10 if !$limit;

$users = Counter::open();

$dbhandle = $FileTable::dbhandle;

#------ Some quite old data -----------

$stm = $dbhandle->prepare("select * from f_log where tablename = 'persons' and data like '%recdate:%' and data like '%method:www unknown\@unknown%' limit $limit");
$stm->execute() || die "Select failed\n";
print $stm->rows, " records with www unknown\@unknown found\n";
while ($r = $stm->fetchrow_hashref()) {
    checkentry($r);
}

#----- Reasonably recent updates ------

$stm = $dbhandle->prepare("select * from f_log  where tablename = 'persons' and  data like '%recdate:%' and data like '%ident:script=cgi-bin/userupdate.cgi%' limit $limit");
$stm->execute() || die "Select failed\n";
print $stm->rows, " records with userupdate.cgi found\n";
while ($r = $stm->fetchrow_hashref()) {
    checkentry($r);
}


print "$reasonable records causing recdate-setting found\n";
print "$badrecdate bad recdates\n";
print "$nochange records already have suggested time\n";    
print "$eventnotrecdate records logged later than recdate\n";


sub checkentry {
    my $r = shift;
    # to get easy handling of the record...
    $file = Counter::openfile($$r{tablename});
    $rec = FileTable::makeobject($file, $$r{reckey}, $$r{data});
    if (!$rec->{recdate} || HTTP::Date::str2time($rec->{recdate}) == 0) {
	++ $badrecdate;
    } elsif (HTTP::Date::time2iso(HTTP::Date::str2time($rec->{recdate}))
	eq $$r{date}) {
	# this is the event that caused the recdate, or reasonable
	# facsimile thereof
	$u = $users->get($$r{reckey});
	if (!$u) {
	    print "No user $$r{reckey}\n";
	    next;
	} elsif ($u->{logintime} lt $$r{date}) {
	    print "$$r{reckey}: Change from $$u{logintime} to $$r{date}\n";
	    $$u{logintime} = $$r{date};
	    $u->patch();
	    ++ $reasonable;
	} else {
	    # print "$$r{reckey}: No change\n";
	    ++ $nochange;
	}
    } else {
	#print "$$r{reckey}: Event not from recdate: ", 
        #$rec->{recdate}, " != ",
	#$$r{date}?$$r{date}:"<no logdate>", "\n";
	++ $eventnotrecdate;
    }
}


